package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.ILock;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private SeckillVoucherServiceImpl seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    public Result seckillVoucher(Long voucherId) {
        //1.根据id查询优惠券信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);

        //2.如果优惠券不存在返回错误信息
        if (seckillVoucher == null) {
            return Result.fail("优惠券不存在");
        }

        //3.获取具体时间，库存信息
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        LocalDateTime endTime = seckillVoucher.getEndTime();
        Integer stock = seckillVoucher.getStock();

        //4.如果不在活动范围内，返回错误信息
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(beginTime) || now.isAfter(endTime)) {
            return Result.fail("不在活动时间范围内");
        }

        //5.如果在活动时间内，判断库存
        //5.1如果库存不足， 返回错误信息
        if (stock < 1) {
            return Result.fail("库存不足");
        }

        //8.返回订单id
        Long userId = UserHolder.getUser().getId();

        //获取分布式锁对象
        ILock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);

        //获取锁
        boolean flag = lock.tryLock(1200);

        //如果获取失败（该用户同时间发了多个请求），返回错误信息
        if(!flag){
            Result.fail("一个人只允许下一单");
        }

        //获取到锁，去下单
        try{
            //获取动态代理（代理对象才能获取到事务）
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally{
            //释放锁（不管有没有成功都要释放锁）
            lock.unLock();
        }

    }

    @Transactional
    public Result createVoucherOrder(Long voucherId){
        //获取用户
        Long userId = UserHolder.getUser().getId();

        //查询该用户是否已下过单
        Long count = query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();

        //如果已下单返回错误
        if(count > 0){
            return Result.fail("用户已过下单，无法继续下单");
        }

        //否则放行
        //5.2如果库存充足则扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if(!success){
            return Result.fail("库存不足，无法扣减库存");
        }

        //6.生成订单唯一id
        long orderId = redisIdWorker.nextId("VOUCHER:ORDER");

        //7.保存订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        return Result.ok(orderId);
    }
}
